#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>
#include <functional>

namespace Server
{
    using namespace std;
    static const std::string defaultIp = "0.0.0.0";
    typedef function<void (int, string,uint16_t,string)> func_t;
    static const int gbuffercap = 1024;
    enum
    {
        ARGC_ERR = 1,
        SOCKFD_ERR,
        BIND_ERR,
        FILE_ERR
    };
    class udpServer
    {
    public:
        udpServer(const func_t& cb,uint16_t port) : _port(port), _ip(defaultIp), _sockfd(-1), _callback(cb)
        {
        }
        void initServer()
        {
            // 创建套接字(socket)
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "create sockfd fail!" << std::endl;
                exit(SOCKFD_ERR);
            }
            cout << "sockfd success" << _sockfd << endl;
            // 建立连接 绑定ip + port
            struct sockaddr_in local;
            bzero(&local, sizeof(local)); // 初始化结构体
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = inet_addr(_ip.c_str()); // string-》uint32_t 2.htonl->inet_addr
            // local.sin_addr.s_addr = INADDR_ANY; //服务器绑定真实写法 也即所有ip地址 只要端口相同全部接收！
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "bind error" << errno << " : " << strerror(errno) << endl;
                exit(BIND_ERR);
            }

            // UDP预备工作完成!
        }
        void start()
        {
            // 服务器本质就是死循环
            char buffer[gbuffercap];
            for (;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer); // 必填
                // 接收别的网络但是相同端口发来的信息，第三第四参数为输入输出型参数
                ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                // 数据是什么？  谁发的？
                if (n > 0)
                {
                    buffer[n] = 0;
                    string clientIp = inet_ntoa(peer.sin_addr); // 函数可以直接完成1.网络字节序转换成主机字节序
                    uint16_t clientport = ntohs(peer.sin_port); // 2.转换成点分十进制
                    string message = buffer;
                    cout<<clientIp<<"["<<clientport<<"]"<<message<<endl;
                    _callback(_sockfd,clientIp,clientport,message);
                }
            }
        }
        ~udpServer()
        {
        }

    private:
        std::string _ip;
        uint16_t _port;
        int _sockfd;
        func_t _callback;
    };

}